//
//  ShowImageViewController.m
//  WoWeibo
//
//  Created by apple on 11-11-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ShowImageViewController.h"
#import "SCGIFImageView.h"
#import "ImageCacheHelper.h"

@interface ShowImageViewController (Internal)

- (void)showLoadingIndicators;
- (void)hideLoadingIndicators;

- (void)showImage:(UIImage *)image;
- (void)showGIF:(SCGIFImageView *)gifImage;

- (IMG_TYPE)checkTypeWithURL:(NSURL *)imageURL;

- (void)hiddenNavigationBar;
- (void)showNavigationBar;

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture;

@end

@implementation ShowImageViewController

@synthesize url;
@synthesize picture;

- (void)dealloc {
    
	[url release];
	[picture release];
	[pictureView release];
    
    url = nil;
    picture = nil;
    pictureView = nil;
    
	[super dealloc];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 460)];
    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    _scrollView.minimumZoomScale = 0.5;
    _scrollView.maximumZoomScale = 2.0;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    [_scrollView addGestureRecognizer:singleTap];
    
	// 初始化导航栏按钮
	//self.title = @"图片浏览";
    //self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.translucent = YES;
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"關閉" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)] autorelease];	
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	[self showLoadingIndicators];
    
    NSData *bigImage = [[ImageCacheHelper sharedImageCacheHelper] getImageByURL:url withDelegate:self];
    if(bigImage != nil) {
    
        [self imageDidDownloadSuccessed:bigImage withURL:url];
    }
}

#pragma mark -
#pragma mark Private Methods.

- (void)hiddenNavigationBar {
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    _isBarHiddened = YES;
}

- (void)showNavigationBar {

    [self.navigationController setNavigationBarHidden:NO animated:YES];
    _isBarHiddened = NO;
}

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture { 

    if(_isBarHiddened) {
    
        [self showNavigationBar];
    }else {
    
        [self hiddenNavigationBar];
    }
}

- (void)showLoadingIndicators {
    
    if (!spinner) {
        spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        
        loadingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
		loadingLabel.backgroundColor = [UIColor clearColor];
        loadingLabel.font = [UIFont systemFontOfSize:20];
        loadingLabel.textColor = [UIColor whiteColor];
        loadingLabel.text = @"正在载入...";
        [loadingLabel sizeToFit];
        
        static CGFloat bufferWidth = 8.0;
        
        CGFloat totalWidth = spinner.frame.size.width + bufferWidth + loadingLabel.frame.size.width;
        
        CGRect spinnerFrame = spinner.frame;
        spinnerFrame.origin.x = (self.view.bounds.size.width - totalWidth) / 2.0;
        spinnerFrame.origin.y = (self.view.bounds.size.height - spinnerFrame.size.height) / 2.0;
        spinner.frame = spinnerFrame;
        [self.view addSubview:spinner];
        [spinner startAnimating];
        
        CGRect labelFrame = loadingLabel.frame;
        labelFrame.origin.x = (self.view.bounds.size.width - totalWidth) / 2.0 + spinnerFrame.size.width + bufferWidth;
        labelFrame.origin.y = (self.view.bounds.size.height - labelFrame.size.height) / 2.0;
        loadingLabel.frame = labelFrame;
        [self.view addSubview:loadingLabel];
    }
}

- (void)hideLoadingIndicators {
    
    if (spinner) {
        
        [spinner stopAnimating];
        [spinner removeFromSuperview];
        [spinner release];
        spinner = nil;
        
        [loadingLabel removeFromSuperview];
        [loadingLabel release];
        loadingLabel = nil;
    }
}

- (IMG_TYPE)checkTypeWithURL:(NSURL *)imageURL {
    
    assert(imageURL != nil);
    
    NSString *urlString = imageURL.absoluteString;
    NSString *suffixString = [[urlString substringWithRange:NSMakeRange(urlString.length - 3, 3)] lowercaseString];
    if([suffixString isEqualToString:@"gif"]) {
    
        return IMG_GIF;
    }else {
        
        return IMG_OTHER;
    }
}

- (void)showImage:(UIImage *)image {
    
    if(pictureView == nil) {
        
        pictureView = [[UIImageView alloc] init];
        pictureView.userInteractionEnabled = NO;
        pictureView.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);        
        [_scrollView addSubview:pictureView];
    }
    
    // Resize image.
    CGSize imageSize = image.size;
    float  imageRatio = image.size.width / image.size.height;
    
    imageSize.width = imageSize.width > 320 ? 320 : imageSize.width;
    if(imageSize.width == 320) {
    
        imageSize.height = imageSize.width / imageRatio;
    }
    pictureView.frame = CGRectMake((320 - imageSize.width) / 2, imageSize.height > 460 ? 0 : ((460 - imageSize.height) / 2), imageSize.width, imageSize.height);
    pictureView.image = image;
    
    // Resize scroll content size.
    _scrollView.contentSize = CGSizeMake(320, imageSize.height > 460 ? imageSize.height : 460);
    
    //Set center.
}

- (void)showGIF:(SCGIFImageView *)gifImage {
    
}

- (void)cancel {
    
	[self dismissModalViewControllerAnimated:YES];
}

- (void)save {
    if(imgType == IMG_GIF) {
    
        UIImageWriteToSavedPhotosAlbum(_gifView.image, nil, nil, nil);
    }else {
        UIImageWriteToSavedPhotosAlbum(self.picture, nil, nil, nil);
    }
	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:nil message:@"儲存成功" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
	[myAlert show];
	[myAlert release];
}

#pragma mark -
#pragma mark ImageLoadingOperationDelegate Support.

- (void)imageDidDownloadSuccessed:(NSData *)imageData withURL:(NSURL *)imageURL {
    
    [self hideLoadingIndicators];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    imgType = [self checkTypeWithURL:imageURL];
    
    if(imgType == IMG_GIF) {
        
        NSData *data = imageData;
        if(data != nil) {
            
            if(_gifView != nil) {
                
                [_gifView release];
                _gifView = nil;
            }
            
            _gifView = [[SCGIFImageView alloc] initWithGIFData:data];
            
            CGSize imageSize = _gifView.image.size;
            float  imageRatio = _gifView.image.size.width / _gifView.image.size.height;
            
            imageSize.width = imageSize.width > 320 ? 320 : imageSize.width;
            if(imageSize.width == 320) {
                
                imageSize.height = imageSize.width / imageRatio;
            }
            
            _gifView.frame = CGRectMake((320.0f - imageSize.width) / 2, imageSize.height > 460 ? 0 : ((460.0f - imageSize.height) / 2), imageSize.width, imageSize.height);
            _scrollView.contentSize = CGSizeMake(320, imageSize.height > 460 ? imageSize.height : 460);
            [_scrollView addSubview:_gifView];
        }
        
    }else if(imgType == IMG_OTHER) {
        
        self.picture = [UIImage imageWithData:imageData];
        [self showImage:[UIImage imageWithData:imageData]];
    }
    
    [self performSelector:@selector(singleTapGestureCaptured:) withObject:nil afterDelay:1.0f];
}

- (void)imageDidDownloadFailed:(NSURL *)imageURL {
    
    [self hideLoadingIndicators];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Support.

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollview {
    
    if(imgType == IMG_GIF) {
    
        return _gifView;
    }
    
    return pictureView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {

    UIView *subView = [scrollView.subviews objectAtIndex:0];
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)? 
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)? 
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, 
                                 scrollView.contentSize.height * 0.5 + offsetY);
}

@end
